package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决请求体的乱码问题
        req.setCharacterEncoding("utf-8");
        String keyword = req.getParameter("keyword");
        UserService userService = new UserServiceImpl();
        List<User> user=userService.fingByName(keyword);
        //解决响应体乱码问题
        resp.setContentType("text/html;charset=utf-8");
        //将这个users转换为json格式的字符串，响应到页面
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        //响应到html
        resp.getWriter().write(json);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
